'use client';
import WebrtcNav from '@/components/WebrtcNav';
import { Key, useEffect, useState } from 'react';
import ProtooTransport, { Peer, WebSocketTransport } from 'protoo-client';
import { Device } from 'mediasoup-client';
import { useProtoo, useRecvTransport, useSendTransport } from '@/lib/roomclient';

const Room = () => {
	const [roomId, setRoomId] = useState('dev');
	const [peers, setPeers] = useState('');
	const [isProducer, setIsProducer] = useState(false);

	useEffect(() => {
		if (typeof window !== 'undefined') {
			const query = new URLSearchParams(window.location.search);
			setRoomId(query.get('roomId') || 'dev');
			setPeers(query.get('peerId') || crypto.randomUUID());
			setIsProducer(query.get('produce') === 'true');
		}
	}, []);
	const { protooPeer, mediasoupDevice, remotePeers, setRemotePeers} = useProtoo(
		`wss://lizhan.fun:4443/?roomId=${roomId}&peerId=${peers}`,
		handleCb,
	);
	const { sendTransportRef, producersRef, createProducer } = useSendTransport(protooPeer!, mediasoupDevice!,isProducer);
	const { recvTransportRef,createConsumer } = useRecvTransport(protooPeer!, mediasoupDevice!,setRemotePeers);
	function handleCb(data:any) {
		createConsumer(data)
	}
	const handleClickAudio = () => {
		navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
			createProducer(stream.getTracks()[0], 'audio');
		});
	};
	useEffect(() => {

	}, []);

	return (
		<div>
			<WebrtcNav text={'join room'}></WebrtcNav>
			<div className='m-2'>
				<button onClick={handleClickAudio} className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
					增加
				</button>

				<div className="mt-4 flex flex-wrap">
					{remotePeers.map((peer) => (
						<div key={peer.id} className="border p-2 m-2 border-gray rounded-md w-1/2 md:w-1/3 lg:w-1/4">
							<h2 className="text-sm">{peer.id}--{peer.displayName}</h2>
							<div className="mt-2">
								{/* {peer.tracks.map((track: { id: Key | null | undefined; }) => (
									<div key={track.id} className="mb-2">
</div>
								))} */}
							</div>
						</div>
					))}
				</div>
			</div>
		</div>
	);
};

export default Room;
